<?php

namespace app\model;

use app\service\AlarmService;
use plugin\admin\app\model\DeviceName;
use support\Model;

class Device extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'devices';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;

    protected $appends = ['alarm_desc'];


    public $fillable = [
        'gateway_id',
        'cl',
        'ph',
        'tds',
        'water',
        'alarm',
        'filter',
        'sn',
        'name',
        'last_send_at',
        'status',
        'auto',
    ];

    public function getAlarmDescAttribute()
    {
        if ($this->alarm == 0) return '';
        return (new AlarmService())->generateAlarmMessage($this);
    }

    public function users()
    {
        return $this->belongsToMany(User::class, 'device_user', 'device_id', 'user_id');
    }

    public function deviceName()
    {
        return $this->belongsTo(DeviceName::class, 'device_name_id', 'id');
    }
}
